//***定义为全局变量***
//标识当前鼠标点击事件是否按钮操作，
var indexDriverBlockFlag = true;

// 标记是否在driver块上触发点击事件
function disableIndexDriverBlockFlag(flag){
	indexDriverBlockFlag = flag;
}

// 给驱动块绑定事件
function bindClickEventForDriverBlock(){
	// 驱动编辑
	$(".driver_group").click(function() {
		if ('block' == $(this).attr("attr") && indexDriverBlockFlag) {
			// 加载页面
			$initContainer.load($basePath+ '/driver/page/driverEdit?driverId='+ $(this).attr("id"));
		}
		disableIndexDriverBlockFlag(true);
	});
}

// 查看驱动日志
function showDriverLog($this){
	// 加载页面
	$initContainer.load($basePath+ '/index/page/log?driverId='+ $this.attr("id"));
}

/** ******************** 下拉菜单 *********************** */
/**
 * 切换驱动下拉菜单
 * 
 * @param $driverId
 *            驱动编码
 * @param $model
 *            驱动模式
 * @param $enable
 *            是否已禁用
 * @param $run
 *            是否正在运行
 * @returns 下拉菜单
 */
function getDriverDropdownMenu($driverId, $model, $enable, $run){
	var menuHtml = '';
	var startHTML ='<li class="start" driverId="'+ $driverId +'" driverUrl="/driver/start"><a href="javascript:;"><i class="fa fa-check-circle-o well-sign-green"></i>&nbsp;&nbsp;启动</a></li>';
	var stopHTML ='<li class="stop" driverId="'+ $driverId +'" driverUrl="/driver/stop"><a href="javascript:;"><i class="fa fa-times-circle-o well-sign-red"></i>&nbsp;&nbsp;停止</a></li>';
	var enableHTML ='<li class="enable" driverId="'+ $driverId +'" driverUrl="/driver/enable"><a href="javascript:;"><i class="fa fa-check-circle-o well-sign-green"></i>&nbsp;&nbsp;恢复</a></li>';
	var disableHTML ='<li class="disable" driverId="'+ $driverId +'" driverUrl="/driver/disable"><a href="javascript:;"><i class="fa fa-ban well-sign-red"></i>&nbsp;&nbsp;禁用</a></li>';
	var editHTML ='<li class="disable" driverId="'+ $driverId +'" driverUrl="/driver/edit"><a href="javascript:;"><i class="fa fa-edit well-sign-green"></i>&nbsp;编辑</a></li>';
	var deleteHTML ='<li class="delete" driverId="'+ $driverId +'" driverUrl="/driver/delete"><a href="javascript:;"><i class="fa fa-trash well-sign-red"></i>&nbsp;&nbsp;删除</a></li>';
	var line = '<li class="divider"></li>';
	
	// 启动：如果为启用 && 未运行
	if($enable && !$run){
		menuHtml += line;
		menuHtml += startHTML;
		menuHtml += editHTML;
	}
	// 停止：如果为启用 && 正在运行
	if($enable && $run){
		menuHtml += line;
		menuHtml += stopHTML;
	}
	
	// 恢复：如果为禁用 && 未运行
	if(!$enable && !$run){
		menuHtml += line;
		menuHtml += enableHTML;
	}
	// 禁用：如果为启用 && 未运行
	if($enable && !$run){
		menuHtml += line;
		menuHtml += disableHTML;
	}
	
	// 删除：如果为禁用 && 未运行
	if(!$enable && !$run){
		menuHtml += line;
		menuHtml += deleteHTML;
	}
	return menuHtml;
}

// 给驱动下拉菜单绑定事件
function bindClickEventForDriverDropdownMenu() {
	$(".driverList .dropdown-menu li").click(function() {
		var $this = $(this);
		var driverId = $(this).attr("driverId");
		var driverUrl = $(this).attr("driverUrl");
		
		// 禁用时，进行权限验证
		if("/driver/disable"==driverUrl){
			// 如果当前为恢复状态
			BootstrapDialog.show({
				title : "警告",
				type : BootstrapDialog.TYPE_DANGER,
				message : "确认禁用？",
				size : BootstrapDialog.SIZE_NORMAL,
				buttons : [ {
					label : "确定",
					action : function(dialog) {
						// 点击弹出框确认禁用后进行二次登陆验证
						dirverLoginAuth(driverId, $this);
						dialog.close();
					}
				}, {
					label : "取消",
					action : function(dialog) {
						dialog.close();
					}
				} ]
			});
			return;
		}
		
		if("/driver/edit"==driverUrl){
			// 加载页面
			$initContainer.load($basePath+ '/driver/page/driverEditConfig?driverId='+ driverId);
			return;
		}
		
		$.post($basePath + driverUrl, {
			"driverId" : driverId
		}, function(data) {
			if (data.success == true) {
				// 加载页面
				$initContainer.load($basePath + '/index');
				bootGrowl(data.resultValue, "success");
			} else {
				bootGrowl(data.resultValue, "danger");
			}
		});
	});
}

// 点击弹出框确认禁用后进行二次登陆验证
function dirverLoginAuth(driverId, $this){
	var dirverLoginHtml='<form class="form-horizontal" role="form">'
						+'<div class="form-group">'
						+'<label class="col-sm-2 control-label">用户名<strong class="driverVerifcateRequired">*</strong></label>'
						+'<div class="col-sm-8">'
						+'<input type="text" class="form-control required" name="username" placeholder="请输入用户名">'
						+'</div>'
						+'</div>'
						+'<div class="form-group">'
						+'<label class="col-sm-2 control-label">密码<strong class="driverVerifcateRequired">*</strong></label>'
						+'<div class="col-sm-8">'
						+'<input type="password" class="form-control required" name="userpwd" placeholder="请输入密码">'
						+'</div>'
						+'</div>'
						+'</form>';
	// 展示二次登录表单
	BootstrapDialog.show({
		title : "登录",
		type : BootstrapDialog.TYPE_DANGER,
		message : dirverLoginHtml,
		size:BootstrapDialog.SIZE_NORMAL,
		buttons : [{
			label : "确定",
			action : function(dialog){
				// 驱动二次登陆验证非空校验
				validateDriverUserLogin(dialog, driverId, $this);
			}
			},{
				label : "取消",
				action : function(dialog){			    
				dialog.close();
			}
		}]
	});	
}

// 驱动二次登陆验证非空校验
function validateDriverUserLogin(dialog, driverId, $this) {
	// 获取表单输入值
	var info = dialog.getModalContent();

	// 如果输入框值为空，则高亮显示
	$(info).find("input.required").each(function() {
		if ($(this).val() != "") {
			$(this).removeClass("driverVerifcateError");
			return true;
		}
		$(this).addClass("driverVerifcateError");
	});
	// 触发 keyup 事件
	$(info).find("input.required").keyup(function() {
		$(this).removeClass("driverVerifcateError");
		if ($(this).val() == "") {
			$(this).addClass("driverVerifcateError");
		}
	});
	// 对登录表单进行非空校验
	var username = $(info).find('input[name="username"]').val();
	var userpwd = $(info).find('input[name="userpwd"]').val();
	if (username != "" && userpwd != "") {
		// 点击确定确认登录请求后台
		$.post($basePath + 'authenticate/login', {
			"username" : username,
			"userpwd" : userpwd
		}, function(data) {
			if (data.success == true) {
				// 登录成功 ,点击弹出框确认禁用后禁用驱动
				disableDiver(driverId, $this);
				dialog.close();
			} else {
				bootGrowl(data.resultValue, "danger");
			}
		});
	}
}

// 禁用驱动
function disableDiver(driverId, $this){
	var driverUrl = $this.attr("driverUrl");
	// 点击确定确认登录请求后台
	$.post($basePath + driverUrl, {
		"driverId" : driverId
	}, function(data) {
		if (data.success == true) {
			// 加载页面
			$initContainer.load($basePath + '/index');
			bootGrowl(data.resultValue, "success");
		} else {
			bootGrowl(data.resultValue, "danger");
		}
	});
}
/** ******************** 下拉菜单 *********************** */

// 给驱动绑定事件
function bindClickEventForDriver() {
	// 给驱动块绑定事件
	bindClickEventForDriverBlock();
	// 给驱动下拉菜单绑定事件
	bindClickEventForDriverDropdownMenu();
}

// 显示左侧驱动列表
function showDirverList(driver,index){
	var driverId = driver.id;
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.targetMapping;
	
	// 驱动logo
	var sourceLogo = getDriverLogo(sourceMapping);
	var targetLogo = getDriverLogo(targetMapping);
	
	// 驱动是否可用
	var diedImage = "fa-times-circle-o well-sign-red";
	var aliveImage = "fa-circle well-sign-green";
	var sourceAliveImg = sourceMapping.alive ? aliveImage : diedImage;
	var targetAliveImg = targetMapping.alive ? aliveImage : diedImage;
	
	// 中间图标
	var runIcon = '<span class="running-through-rate well-sign-green">✔</span>';
	var notRunIcon = '<span class="running-through-rate well-sign-red">✘</span>';
	var disabledIcon = '<span class="running-through-rate"><i class="fa fa-ban well-sign-red"></i></span>';
	// 中间文本
	var disabledText = '<span class="running-state text-warning">已禁用</span>';
	var notRunText = '<span class="running-state">未运行</span>';
	var runText = '<span class="running-state text-success">运行中</span>';
	var enableIconHtml = driver.run ? runIcon : notRunIcon;
	var startOrStopHtml = driver.run ? runText : notRunText;

	// 检查是否已禁用
	enableIconHtml = driver.enable ? enableIconHtml : disabledIcon;
	startOrStopHtml = driver.enable ? startOrStopHtml : disabledText;
	
	// 下拉菜单
	var dropdownMenu = getDriverDropdownMenu(driverId, driver.model, driver.enable, driver.run);
	
	var html= '';
	html +='<div class="row driverList">';
	html +='<div class="col-md-12">';
	html +='<div id='+ driverId +' class="jumbotron driver_group" attr="block">';

	html += "<!--驱动标题信息 -->";
	html +='<div class="row">';
	html +='<div class="col-md-12">';
	html +='<p class="driver-title">';
	html +='<span class="driver-app-order">'+index+'</span>';
	html +='<span class="driver-app-name">&nbsp;'+driver.appName+'</span>';
	html +='</p>';
	html +='</div>';
	html +='</div>';
	html +='<div class="row text-center">'+driver.name+'</div>';
	
	html +='<div class="row">';
	html += "<!--左边驱动信息 -->";	
	html +='<div class="col-md-4">';
	html +='<div class="well well-lg">';
	html +='<div class="col-md-4">';
	html +='<img src="'+sourceLogo+'">';
	html +='</div>';
	html +='<div class="col-md-8">';
	html +='<span title="'+sourceMapping.name+'">'+sourceMapping.name +'</span>';
	html +='</div>';
	html +='</div>';
	html +='<span class="well-sign-left"><i class="fa fa-2x '+sourceAliveImg+'"></i></span>';
	html +='</div>';

	html += "<!--中间图标 -->";
	html +='<div class="col-md-4">';
	html +='<div class="line">';
	html += enableIconHtml;
	html +=	startOrStopHtml;
	html +='</div>';
	html +='</div>';
		
	html += "<!-- 右边驱动信息 -->";	
	html +='<div class="col-md-4">';			
	html +='<div class="well well-lg">';					
	html +='<div class="col-md-4">';
	html +='<img src="'+targetLogo+'">';
	html +='</div>';
	html +='<div class="col-md-8">';
	html +='<span title="'+targetMapping.name+'">'+targetMapping.name +'</span>';
	html +='</div>';
	html +='<span class="well-sign-right"><i class="fa fa-2x '+targetAliveImg+'"></i></span>';					
	html +='</div>';
	html +='</div>';
	html +='</div>';
	html +='</div>';
	html +='</div>';
	
	html += "<!-- 下拉菜单 -->";
	html +='<div class="dropdown">';
	html +='<a data-toggle="dropdown" href="javascript:;"><span class="well-sign-operation"><i class="fa fa-gears fa-2x"></i></span></a>';
	html +='<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">'+dropdownMenu+'</ul>';
	html +='</div>';
	// 驱动块结束位置
	html +='</div>';
	return html;
}

// 显示右侧驱动列表
function showDriverDetails(driver,order){
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.targetMapping;
	// 数据迁移/数据同步模式
	var syncModeText = driver.model == "all" ? "数据迁移" : "数据同步";
	// 运行时间
	var startDateStrHtml = driver.startDateStr;
	// 同步数据量,如果是数据迁移，就显示数据源总数
	var total = driver.model == "all" ? sourceMapping.rowCount : (driver.success+driver.fail);
	// 数据迁移
	var process = driver.process;
	var processCompleted = driver.processCompleted;
	// 计算百分百,精确.后两位
	var processText = processCompleted > 0 ? ((processCompleted / process) * 100).toFixed(2) + "%" : '0%';
	processText = processCompleted>=process ? "100%" : processText;
	// 耗时
	var runTimeText = driver.runTime == null ? '0' : driver.runTime;
	var syncText = driver.model == "all" ? '进度：'+processText+'，耗费时间：'+runTimeText+'毫秒' : '';
	// 下载错误日志
	var logText = ', <a href="javascript:;" id="'+driver.id+'" onclick="showDriverLog($(this))" title="查看错误日志" style="color:#990;">查看错误日志</a>';
	logText = driver.fail > 0 ? logText : '';
	
	// 驱动详细信息
	var desc = '';
	desc += '<b style="font-size:16px;">'+order+'</b>&nbsp;'+syncModeText+'>> '+driver.name+' 已运行：'+startDateStrHtml+'<br/>';
	desc += '总数据：'+total+'，成功:'+driver.success+'，失败:'+driver.fail+logText+'<br/> ';
	desc += syncText;
	
	var html = '';
	html += '<tr>'
	html += '<td>'+desc+'</td>';
	html += '</tr>';
	return html;
}

// 统计各个连接器个数:database,webservice,ldap,redis
function showConnectornNumber(drivers) {
	var dataBaseSum = 0;
	var webServiceSum = 0;
	var ldapSum = 0;
	var redisSum = 0;
	
	// 循环获取的驱动列表
	$.each(drivers, function(i, val) {
		var sourceConnector = drivers[i].sourceMapping.connector;
		var targetConnector = drivers[i].targetMapping.connector;
		// 获取database连接器个数
		if (sourceConnector == ConnectorConstantMysql || sourceConnector == ConnectorConstantOracle || sourceConnector == ConnectorConstantSqlServer) {
			dataBaseSum++;
		}
		if (targetConnector == ConnectorConstantMysql || targetConnector == ConnectorConstantOracle || targetConnector == ConnectorConstantSqlServer) {
			dataBaseSum++;
		}
		// 获取webservice连接器个数
		if (sourceConnector == ConnectorConstantWebService) {
			webServiceSum++;
		}
		if (targetConnector == ConnectorConstantWebService) {
			webServiceSum++;
		}
		// 获取ldap连接器个数
		if (sourceConnector == ConnectorConstantLdap) {
			ldapSum++;
		}
		if (targetConnector == ConnectorConstantLdap) {
			ldapSum++;
		}
		// 获取ldap连接器个数
		if (sourceConnector == ConnectorConstantRedis) {
			redisSum++;
		}
		if (targetConnector == ConnectorConstantRedis) {
			redisSum++;
		}
	});
	// 分别展示各个连接器个数
	$('#dataBaseCount').text(dataBaseSum);
	$('#webServiceCount').text(webServiceSum);
	$('#ldapCount').text(ldapSum);
	$('#redisCount').text(redisSum);
}

// 更新驱动列表实时状态
function refreshDriversList() {
	// 第三方业务系统ID,用于标记多个窗口
	if(null==$thirdPartyAppId || ''==$thirdPartyAppId){
		$thirdPartyAppId = $("#appId").text();
	}
	
	// 保存驱动配置
	$.post($basePath + "/index/getDriverAll", {'appId':$thirdPartyAppId}, function(data) {
		if (data.success == true) {
			var drivers = data.resultValue;
			var driversLen = drivers.length;
			var listHtml = driversLen < 1 ? '未添加驱动.' : '';
			var trsHtml = '';	
			// 统计各个连接器个数，包括database，webservice，ldap和csv
			showConnectornNumber(drivers);
			for (var i = 0; i < driversLen; i++) {
				listHtml += showDirverList(drivers[i],i+1);
				trsHtml += showDriverDetails(drivers[i], i + 1);
			}
			// 向左侧面板添加驱动列表
			$("#dirverList").html(listHtml);
			// 向右侧表格添加驱动列表详细信息
			$("#driverListDetails").html(trsHtml);
			// 重新绑定驱动事件
			bindClickEventForDriver();
		} else {
			// 请求失败
			bootGrowl("访问被拒绝,请重新访问.", "danger");
			// 刷新页面
			location.reload();
		}
	});
}

$(function() {
	// 添加驱动按钮事件
	$("#indexAddDriverBtn").click(function() {
		// 加载页面
		$initContainer.load($basePath + '/driver/page/driverAdd?refresh='+new Date().getTime());
	});
	
	// 更新驱动列表实时状态
	refreshDriversList();

	// $$monitorFreshListIntervalStarted变量防止导致定时任务刷新JS被重复执行
	if (!$monitorFreshListIntervalStarted) {
		// 驱动列表实时刷新
		setInterval('refreshDriversList()', 5000);
		$monitorFreshListIntervalStarted = true;
	}

	// 绑定驱动块事件
	bindClickEventForDriver();
});
